using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;

namespace Behemoth.SharePoint.Administration {

    public partial class WebConfigModificationAdmin : Microsoft.SharePoint.WebControls.LayoutsPageBase {

        protected Label idAddError;
        protected TextBox idName;
        protected TextBox idValue;
        protected TextBox idPath;
        protected TextBox idSequence;
        protected TextBox idOwner;
        protected DropDownList idType;

        protected WebApplicationSelector selector;
        //protected WebModificationsGrid WebModificationsGrid1;

        protected void Page_Load(object sender, EventArgs e) {

        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            // bind the selector to our edit grid control... there are better ways to do this obviously...
            //WebModificationsGrid1.WebAppSelector = selector;
        }

        protected void OnContextChange(object sender, EventArgs e) {
        }

        protected void DeleteSelected(object sender, EventArgs e) {
            string[] arKeys = Page.Request.Form.AllKeys;

            SPWebApplication oApp = selector.CurrentItem;

            int iStartCount = oApp.WebConfigModifications.Count;

            List<int> l = new List<int>();

            foreach (string sKey in arKeys) {
                if (sKey.StartsWith("checkedItem"))
                    l.Add(int.Parse(sKey.Substring(11)));
            }

            for (int i = l.Count - 1; i >= 0; i--)
                oApp.WebConfigModifications.Remove(oApp.WebConfigModifications[l[i]]);

            if (oApp.WebConfigModifications.Count < iStartCount) {
                oApp.Update();
                oApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
        }

        protected void UpdateSelected(object sender, EventArgs e) {
            Collection<SPWebConfigModification> UpdateWebConfigModifications = new Collection<SPWebConfigModification>();

            string[] arKeys = Page.Request.Form.AllKeys;

            SPWebApplication oApp = selector.CurrentItem;

            List<int> l = new List<int>();

            foreach (string sKey in arKeys) {
                if (sKey.StartsWith("checkedItem")) {
                    l.Add(int.Parse(sKey.Substring(11)));
                }
            }

            for (int i = 0; i < l.Count; i++) {
                SPWebConfigModification wm = (SPWebConfigModification)oApp.WebConfigModifications[l[i]];
                SPWebConfigModification wmUpdate = new SPWebConfigModification(wm.Name, wm.Path);
                wmUpdate.Sequence = wm.Sequence;
                wmUpdate.Type = wm.Type;

                string updateItem = "updateItem" + l[i];
                string updateItemValue = Request.Form[updateItem];

                if (updateItemValue != "" && updateItemValue != wm.Value) {
                    wmUpdate.Owner = String.Format("{0}_{1}_{2:F}", wm.Name, wm.Path, DateTime.Now);
                    wmUpdate.Value = updateItemValue;
                    UpdateWebConfigModifications.Add(wmUpdate);
                }
            }

            if (UpdateWebConfigModifications.Count > 0) {
                for (int wa = 0; wa <= UpdateWebConfigModifications.Count - 1; wa++) {
                    oApp.WebConfigModifications.Add(UpdateWebConfigModifications[wa]);
                }

                oApp.Update();
                oApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
        }

        protected bool IsValidAdd() {
            idAddError.Text = "";

            // Skip validation
            if (Page.Request["novalidation"] == "1") return true;

            if (idOwner.Text == "")
                idAddError.Text = "Please specify an owner";

            else if (idValue.Text == "")
                idAddError.Text = "Please enter the value";

            else if (idPath.Text == "")
                idAddError.Text = "Please specify the path";

            else if (idName.Text == "" || idName.Text.StartsWith("@"))
                idAddError.Text = "Please specify the path";

            else if (idType.SelectedValue == "0") {
                try {
                    // Validate the entry
                    System.Xml.XmlDocument oDoc = new System.Xml.XmlDocument();
                    oDoc.LoadXml("<Test>" + idValue.Text + "</Test>");
                    System.Xml.XmlNode oNode = oDoc.DocumentElement.SelectSingleNode(idName.Text);
                    if (oNode == null)
                        idAddError.Text = "Name is not compatible with the value";
                } catch (Exception ex) {
                    idAddError.Text = "Invalid value: " + ex.Message;
                }

            }

            return (idAddError.Text != "") ? false : true;
        }

        protected void AddEntry(object sender, EventArgs e) {
            if (!IsValidAdd()) return;

            SPWebApplication oApp = selector.CurrentItem;

            SPWebConfigModification wm = new SPWebConfigModification(idName.Text, idPath.Text);
            wm.Owner = idOwner.Text;
            wm.Sequence = uint.Parse(idSequence.Text);
            wm.Type = (idType.SelectedValue == "0") ? SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode : (idType.SelectedValue == "1") ? SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute : SPWebConfigModification.SPWebConfigModificationType.EnsureSection;
            wm.Value = idValue.Text;

            //Page.Response.Write(idType.SelectedValue);

            oApp.WebConfigModifications.Add(wm);
            oApp.Update();
            oApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
        }

    } // class

} // namespace

